// Copyright 2024 Xiguan Inc
// Author: xiguan
// Email: xiguan.teng@qq.com
// Created on 2024/8/6
// This is ...
//

#include "helper.h"

#include <absl/flags/flag.h>
#include <absl/log/log.h>
#include <route_guide.grpc.pb.h>
#include <route_guide.pb.h>

#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

ABSL_FLAG(std::string, db_path,
          "/root/codes/MIT8.624/mit6824_labs/grpc_learn/route_guide.json",
          "Path to db file");

namespace routeguide {
class Parser {
 public:
  explicit Parser(const std::string &db) : db_(db) {
    // Remove all spaces.
    db_.erase(std::remove_if(db_.begin(), db_.end(), isspace), db_.end());
    if (!Match("[")) {
      SetFailedAndReturnFalse();
    }
  }

  bool Finished() { return current_ >= db_.size(); }

  bool TryParseOne(Feature *feature) {
    if (failed_ || Finished() || !Match("{")) {
      return SetFailedAndReturnFalse();
    }
    if (!Match(location_) || !Match("{") || !Match(latitude_)) {
      return SetFailedAndReturnFalse();
    }
    long temp = 0;
    ReadLong(&temp);
    feature->mutable_location()->set_latitude(temp);
    if (!Match(",") || !Match(longitude_)) {
      return SetFailedAndReturnFalse();
    }
    ReadLong(&temp);
    feature->mutable_location()->set_longitude(temp);
    if (!Match("},") || !Match(name_) || !Match("\"")) {
      return SetFailedAndReturnFalse();
    }
    size_t name_start = current_;
    while (current_ != db_.size() && db_[current_++] != '"') {
    }
    if (current_ == db_.size()) {
      return SetFailedAndReturnFalse();
    }
    feature->set_name(db_.substr(name_start, current_ - name_start - 1));
    if (!Match("},")) {
      if (db_[current_ - 1] == ']' && current_ == db_.size()) {
        return true;
      }
      return SetFailedAndReturnFalse();
    }
    return true;
  }

 private:
  bool SetFailedAndReturnFalse() {
    failed_ = true;
    return false;
  }

  bool Match(const std::string &prefix) {
    bool eq = db_.substr(current_, prefix.size()) == prefix;
    current_ += prefix.size();
    return eq;
  }

  void ReadLong(long *l) {
    size_t start = current_;
    while (current_ != db_.size() && db_[current_] != ',' &&
           db_[current_] != '}') {
      current_++;
    }
    // It will throw an exception if fails.
    *l = std::stol(db_.substr(start, current_ - start));
  }

  bool              failed_ = false;
  std::string       db_;
  size_t            current_   = 0;
  const std::string location_  = "\"location\":";
  const std::string latitude_  = "\"latitude\":";
  const std::string longitude_ = "\"longitude\":";
  const std::string name_      = "\"name\":";
};

std::string GetDbFileContent(int argc, char **argv) {
  std::string   db_path = absl::GetFlag(FLAGS_db_path);
  std::ifstream db_file(db_path);
  if (!db_file.is_open()) {
    LOG(ERROR) << "Failed to open " << db_path;
    abort();
  }
  std::stringstream db;
  db << db_file.rdbuf();
  return db.str();
}

void ParseDb(const std::string &db, std::vector<Feature> *feature_list) {
  feature_list->clear();
  auto db_content(db);
  db_content.erase(
      std::remove_if(db_content.begin(), db_content.end(), isspace),
      db_content.end());

  Parser  parser(db_content);
  Feature feature;
  while (!parser.Finished()) {
    feature_list->push_back(Feature());
    if (!parser.TryParseOne(&feature_list->back())) {
      LOG(ERROR) << "Error parsing the db file";
      feature_list->clear();
      break;
    }
  }
  LOG(INFO) << "DB parsed, loaded " << feature_list->size() << " features.";
}
}  // namespace routeguide
